package com.feihua.honest;

import android.app.*;
import android.os.*;
import android.util.*;
import android.view.*;

import java.util.*;
import javax.net.ssl.*;
import javax.security.cert.*;
import okhttp3.*;
import org.json.*;
import java.text.*;
import com.feihua.honest.bean.*;
import com.feihua.honest.adapter.*;
import java.io.*;
import java.security.*;
import android.support.v7.app.*;
import android.support.v7.widget.Toolbar;
import android.widget.*;
import com.tencent.smtt.sdk.*;
import com.feihua.dialogutils.util.*;

public class MainActivity extends AppCompatActivity 
{
	WebView wv_main;
	private List<Honest> data;
	private ListView lv_list;
	private HonestAdapter honestAdapter;
	private Toolbar toolbar;
	private RelativeLayout rl_web;
	private TextView tv_toast;
	
	DialogUtils du;
	
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		
		initView();
		
    }
	private String CookieStr;
	

	public void bt(View v){
		wv_main.loadUrl("https://ti.qq.com/honest-say/my-received.html?_wv=9191&_wwv=132&_qStyle=1&ADTAG=main");
	}
	
	
	private void initView()
	{
		QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {


			@Override
			public void onViewInitFinished(boolean arg0) {
				// TODO Auto-generated method stub
				//x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
				//Log.e(TAG, " 回调结果 = " + arg0);
			}

			@Override
			public void onCoreInitFinished() {
				// TODO Auto-generated method stub
			}
		};
		QbSdk.initX5Environment(this,null);
		
		
		wv_main=(WebView) findViewById(R.id.wv_main);
		lv_list=(ListView) findViewById(R.id.lv_list);
		rl_web=(RelativeLayout) findViewById(R.id.rl_web);
		tv_toast=(TextView) findViewById(R.id.tv_toast);
		du=DialogUtils.getdx(this);
		du.dialogt1("这是神奇的说明喵~","Q:为什么要登录\nA:因为需要QQ的cookie\n\nQ:为什么不能快捷登录\nA:同上\n\nQ:为什么有些QQ是问号\nA:问号表示0~9的其中一个数字,因为没解析出来,所以用问号代替");
		toolbar=(Toolbar) findViewById(R.id.toolbar);
		toolbar.setTitle("坦白说查询");
		lv_list.setVisibility(View.GONE);
		tv_toast.setVisibility(View.GONE);
		WebSettings webSetting= wv_main.getSettings();
		webSetting.setJavaScriptEnabled(true);
		webSetting.setUserAgentString("Mozilla/5.0 (Linux; Android 8.0; MI 6 Build/OPR1.170623.027; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/044006 Mobile Safari/537.36 V1_AND_SQ_7.5.5_806_YYB_D QQ/7.5.5.3460 NetType/4G WebP/0.3.0 Pixel/1080");
		
		data=new ArrayList<Honest>();
		honestAdapter=new HonestAdapter(this,data);
		lv_list.setAdapter(honestAdapter);
		
		setWebViewListener();
		wv_main.loadUrl("https://ui.ptlogin2.qq.com/cgi-bin/login?pt_hide_ad=1&style=9&pt_ttype=1&appid=549000929&pt_no_auth=1&pt_wxtest=1&daid=5&s_url=https%3A%2F%2Fh5.qzone.qq.com%2Fmqzone%2Findex");
		
		// TODO: Implement this method
	}
	
	private void setWebViewListener()
	{
		wv_main.setWebChromeClient(new WebChromeClient() {
				public static final String TAG = "主窗口";

				
				public void onProgressChanged(WebView view, int progress) {

					//加载完成
					if (progress == 100) {
						if (wv_main.getUrl().equals("https://h5.qzone.qq.com/mqzone/index")) {

							CookieManager cookieManager = CookieManager.getInstance();
							 CookieStr = cookieManager.getCookie("https://h5.qzone.qq.com/mqzone/index");
						//	Toast.makeText(getApplicationContext(), CookieStr, Toast.LENGTH_LONG).show();
						//	Log.e("cok为","为"+CookieStr);
							wv_main.loadUrl("https://ti.qq.com/honest-say/my-received.html?_wv=9191&_wwv=132&_qStyle=1&ADTAG=main");
						}
								

						
					}
				}
			});
		wv_main.setWebViewClient(new WebViewClient() {
				//覆盖shouldOverrideUrlLoading 方法
				@Override
				public boolean shouldOverrideUrlLoading(WebView view, String url) {
					try {
						if (url.startsWith("jsbridge://")) {
							return false;
						}
					} catch (Exception e) {
						return false;
					}
					wv_main.loadUrl(url);
					return true;
				}

				@Override
				public void onLoadResource(WebView view, final String url) {
					
					if (url.indexOf("cgi-node/honest-say/receive/mine?_client_version=") != -1) {
						new Thread(new Runnable(){

								@Override
								public void run()
								{
									try
									{
										GetHonestsayData(url);
										handler.sendEmptyMessage(0);
									}catch (Exception e){
										Message message=new Message();
										message.what=1;
										message.obj=e;
										handler.sendMessage(message);
										
									}
									// TODO: Implement this method
								}
							}).start();
					}

					super.onLoadResource(view, url);
				}

			});
		// TODO: Implement this method
	}
	
	
	Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg)
		{
			// TODO: Implement this method
			super.handleMessage(msg);
			
			switch(msg.what){
				case 0:
					rl_web.setVisibility(View.GONE);
					if(data.size()!=0){
					lv_list.setVisibility(View.VISIBLE);
					}else{
						tv_toast.setVisibility(View.VISIBLE);
						
					}
					honestAdapter.sx();
					break;
				case 1:
					show("加载失败,原因为"+msg.what);
					break;
				
			}
		}

		
	};
	
	private void show(String message)
	{
		Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
		// TODO: Implement this method
	}

	
	
	public void GetHonestsayData(String frindData) throws JSONException, ParseException, IOException, KeyManagementException, NoSuchAlgorithmException {
        String str = getjsonstr(frindData);
		Log.e("返回","返回为"+str);
             JSONObject json = new JSONObject(str);
            JSONObject json_data = json.getJSONObject("data");
            JSONArray json_list = json_data.getJSONArray("list");
            for (int i = 0; i < json_list.length(); i++) {
                JSONObject json_listobj = json_list.getJSONObject(i);
				String fromEncodeUin=json_listobj.getString("fromEncodeUin");
                String QQ=HonestsayFind.parse(fromEncodeUin);
				QQ=QQ.replace("null","?");
				Log.e("qq对比","前为"+fromEncodeUin);
				Log.e("qq对比","后为"+QQ);
				Honest honest=new Honest();
				honest.setFromNick(json_listobj.getString("fromNick"));
				honest.setTopicName(json_listobj.getString("topicName"));
				Date date=transForDate(json_listobj.getLong("timestamp"));
				
				DateFormat format = new SimpleDateFormat("MM-dd HH:mm");   
				honest.setTime(format.format(date));
				honest.setFromQQ(QQ);
				data.add(honest);
            }   
    }

    /** 
     * 时间戳转日期 
     * @param ms 
     * @return 
     */  
    public static Date transForDate(long ms) throws ParseException{  
        
        long msl=ms*1000;  
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date temp=null;  
        if(ms!=0){  
           
                String str=sdf.format(msl);  
                temp=sdf.parse(str);  
          
        }  
        return temp;  
    }  
    public String getjsonstr(String url) throws IOException, KeyManagementException, NoSuchAlgorithmException {
		
        OkHttpClient client = getUnsafeOkHttpClient();
        String Htmldata = "";
        
            Request request = new Request.Builder()
				.url(url).addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 8.0; MI 6 Build/OPR1.170623.027; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/044006 Mobile Safari/537.36 V1_AND_SQ_7.5.5_806_YYB_D QQ/7.5.5.3460 NetType/4G WebP/0.3.0 Pixel/1080")
				.header("Cookie", CookieStr)
				.build();//创建Request 对象
            Response response = null;
            response = client.newCall(request).execute();//得到Response 对象
            if (response.isSuccessful()) {
                Htmldata = response.body().string();
            }
    
        return Htmldata;
    }
	private static OkHttpClient getUnsafeOkHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
        
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
				new X509TrustManager() {
					@Override
					public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)  {
					}

					@Override
					public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)  {
					}

					@Override
					public java.security.cert.X509Certificate[] getAcceptedIssuers() {
						return new java.security.cert.X509Certificate[]{};
					}
				}
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
					@Override
					public boolean verify(String hostname, SSLSession session) {
						return true;
					}
				});
            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
    
    }
}
